# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(optparse)
library(ggrepel)
library(tidyverse)
library(magrittr)
library(extrafont)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--pc", default = "variance_plot_config.txt", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

parent <- "./"
createWhenNoExist(parent)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))

pdf(paste0(parent, "/PCA_Screeplot.pdf"), width = width, height = height)

parameterFileName <- paste0(parent, "/PCA_R2.csv")
parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")
baseFamily<-fontFamily

lineData <- parameterData %>%
    column_to_rownames("X") %>%
    t() %>%
    as.data.frame() %>%
    select(c("R2")) %>%
    rename(value = R2) %>%
    mutate(value=value*100) %>%
    mutate(sum = cumsum(value)) %>%
    rownames_to_column("index")
lineData

plotData <- lineData %>%
gather("Class", "value", - index)
plotData

labelData <- plotData %>%
    select(- c("Class")) %>%
    as.data.frame() %>%
    unique() %>%
    mutate(label = paste0(value, "%"))

labelData

p <- ggplot(plotData, aes(x = index, y = value)) +
    xlab("PC index") +
    ylab("Variance Explained (%)") +
    theme_bw(base_size = 8.8, base_family = baseFamily) +
    theme(axis.text.x = element_text(size = 9, vjust = 0.5),
    axis.text.y = element_text(size = 8.8), legend.position = 'none',
    axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
    legend.text = element_text(size = 6), axis.title.x = element_text(size = 11),
    panel.grid.major.y = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank(),
    plot.title = element_text(hjust = 0.5, size = 13)
    ) +
    geom_line(aes(x = index, y = value, group = 1), lineData, size = 0.5, linetype = 1, color = "blue") +
    geom_line(aes(x = index, y = sum, group = 1), lineData, size = 0.5, linetype = 1, color = "green") +
    geom_point(size = 2, pch = 21, color = "red") +
    geom_text_repel(segment.size=0.2,data = labelData, aes(x = index, y = value, label = label), color = "black", size = 2, family = baseFamily)

p <- getBasicPlotArg(p)

p
dev.off()
